package laba8;

import java.io.FileInputStream;
import java.io.IOException;

import interfaces.task8.PathClassLoader;

/**
 * The custom ClassLoader.
 *
 * @author yakimovich
 *
 */
public class PathClassLoaderImpl extends ClassLoader
        implements PathClassLoader {

    private String path;

    /**
     * Get path
     *
     * @return String path
     */
    @Override
    public String getPath() {
        return path;
    }

    /**
     * Set path.
     *
     * @param path the specified class
     */
    @Override
    public void setPath(String path) {
        if (path == null) {
            throw new NullPointerException();
        }
        this.path = path;
    }

    @Override
    protected Class findClass(String name)
            throws ClassNotFoundException {

        try {
            byte[] buf = loadClassData(name);
            return defineClass(name, buf, 0, buf.length);
        } catch (IOException e) {
            throw new ClassNotFoundException();
        }
    }

    protected byte[] loadClassData(String name)
            throws IOException,
            ClassNotFoundException {

        FileInputStream in = null;
        try {
            String file = path + "/" + name + ".class";
            in = new FileInputStream(file);
            int len = in.available();
            if (len == 0) {
                throw new ClassNotFoundException();
            }
            byte[] buf = new byte[len];
            in.read(buf);
            return buf;
        } finally {
            if (in != null) {
                in.close();
            }
        }
    }
}
